package com.ziq.zcamp.post

import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.facebook.imagepipeline.request.ImageRequest
import com.ziq.base.extension.BindingViewHolder
import com.ziq.base.extension.click
import com.ziq.base.extension.createBindingViewHolder
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.databinding.ItemCommunityRecommendedBinding
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.PictureUtil
import com.ziq.zcamp.util.StringUtil

class PostingAdapter(val itemWidth:Int, val showViewCount:Boolean=false
,var dataList: List<PostingDetail>) : RecyclerView.Adapter<BindingViewHolder<ItemCommunityRecommendedBinding>>(){

    constructor(itemWidth:Int, showViewCount:Boolean=false) : this(itemWidth,showViewCount,mutableListOf<PostingDetail>())

    interface PostingAdapterAction{
        fun itemClick(item:PostingDetail)
        fun userInfoClick(item:PostingDetail)
    }

//    private var dataList = mutableListOf<PostingDetail>()
    private var postingAdapterAction:PostingAdapterAction? = null
    fun setData(list: MutableList<PostingDetail>) {
        dataList = list
        notifyDataSetChanged()
    }

    fun setPostingAdapterAction(postingAdapterAction:PostingAdapterAction){
        this.postingAdapterAction = postingAdapterAction
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BindingViewHolder<ItemCommunityRecommendedBinding> {
        return createBindingViewHolder(parent)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun onBindViewHolder(
        holder: BindingViewHolder<ItemCommunityRecommendedBinding>,
        position: Int
    ) {
        val item = dataList[position]
        holder.itemView.click {
            postingAdapterAction?.itemClick(item)
        }

        if(item.post?.p_type == 2){
            holder.binding.ivPostTypeLabel.visibility = View.VISIBLE
            holder.binding.ivPostTypeLabel.setImageResource(R.drawable.icon_post_video_label)
        } else {
            holder.binding.ivPostTypeLabel.visibility = View.GONE
        }

        if(showViewCount){
            holder.binding.llViewCount.visibility = View.VISIBLE
            holder.binding.tvViewCount.text = StringUtil.formatCodeForWanUnit(item.view_count)
        } else {
            holder.binding.llViewCount.visibility = View.GONE
        }

        holder.binding.llUserInfo.click {
            postingAdapterAction?.userInfoClick(item)
        }

        if(position == 0 || position == 1){
            val marginTop: Int = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_12)
            val lp = holder.binding.cardview.layoutParams as FrameLayout.LayoutParams
            lp.topMargin = marginTop
            holder.binding.cardview.layoutParams = lp
        }

        var content = ""
        if(item.post?.title?.isNotEmpty() == true){
            content = "${item.post?.title}"
        }else if(item.post?.content?.isNotEmpty() == true){
            content = "${item.post?.content}"
        }
        if (content.isEmpty()){
            holder.binding.title.visibility = View.GONE
            val paddingtop = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_12)
            val lp = holder.binding.avator.layoutParams as LinearLayout.LayoutParams
            lp.topMargin = paddingtop
            lp.bottomMargin = paddingtop
            holder.binding.avator.layoutParams = lp
        } else {
            holder.binding.title.visibility = View.VISIBLE
            val paddingtop = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_8)
            val lp = holder.binding.avator.layoutParams as LinearLayout.LayoutParams
            lp.topMargin = paddingtop
            lp.bottomMargin = paddingtop
            holder.binding.avator.layoutParams = lp
        }

        holder.binding.title.text = content
        holder.binding.name.text = "${item.user?.nick_name}"
        ImageUtil.updateImageFromNetwork(holder.binding.avator, item.user?.header_url, ImageRequest.CacheChoice.DEFAULT)

        val imageInfo = item.post?.images?.get(0)
        if(imageInfo != null){
            val params = holder.binding.image.layoutParams as ViewGroup.LayoutParams
            params.width = itemWidth
            params.height = PictureUtil.calculatePictureViewHeight(itemWidth, imageInfo.width, imageInfo.height)
            holder.binding.image.layoutParams = params

            ImageUtil.updateImageFromNetwork(holder.binding.image, imageInfo.url, ImageRequest.CacheChoice.DEFAULT)

        } else {
            val params = holder.binding.image.layoutParams as ViewGroup.LayoutParams
            params.width = itemWidth
            params.height = itemWidth
            holder.binding.image.layoutParams = params
        }


        updateLikeUI(true, item, holder)

        holder.binding.llCommentActionPraise.click {
            LoginActivity.checkLogin( object : ActionAfterLogin {
                override fun action() {
                    //点赞 帖子
                    if(holder.binding.llCommentActionPraise.isSelected){
                        updateItemDataForUnLike(item, holder)
                        UserManager.instance.unlikePosting(item.post?.post_id?:"", item.user?.uid?:0, item.post?.like_nums?:0,
                            onFail = {
                                updateItemDataForLike(item, holder)
                            }
                        )
                    } else {
                        updateItemDataForLike(item, holder)
                        UserManager.instance.likePosting(item.post?.post_id?:"", item.user?.uid?:0, item.post?.like_nums?:0,
                            onFail = {
                                updateItemDataForUnLike(item, holder)
                            }
                        )
                    }
                }
            })
        }
    }

    fun updateItemDataForLike(item: PostingDetail, holder: BindingViewHolder<ItemCommunityRecommendedBinding>){
        item.post?.let {
            val likeNum = it.like_nums?:0
            it.like_nums = likeNum + 1
            it.is_like = true
        }
        updateLikeUI(false,item, holder)
    }

    fun updateItemDataForUnLike(item: PostingDetail, holder: BindingViewHolder<ItemCommunityRecommendedBinding>){
        item.post?.let {
            val likeNum = it.like_nums?:0
            if(likeNum > 0 ){
                it.like_nums = likeNum - 1
            }
            it.is_like = false
        }
        updateLikeUI(false, item, holder)
    }

    fun updateLikeUI(considerManager: Boolean, item: PostingDetail, holder: BindingViewHolder<ItemCommunityRecommendedBinding>){
        var likeNum = item.post?.like_nums?:0
        if(considerManager && item.post?.post_id?.isNotEmpty() == true && UserManager.instance.postingLike.value?.contains(item.post?.post_id) == true){
            holder.binding.llCommentActionPraise.isSelected = UserManager.instance.postingLike.value!![item.post!!.post_id]!!.isLike
            likeNum = UserManager.instance.postingLike.value!![item.post!!.post_id]!!.num
            item.post?.like_nums = likeNum
        } else {
            holder.binding.llCommentActionPraise.isSelected = item.post?.is_like?:false
        }
        holder.binding.tvCommentActionPraiseCount.visibility = View.VISIBLE
        if(likeNum > 10000){
            holder.binding.tvCommentActionPraiseCount.text = String.format("%.1f", (likeNum / 10000.0)) + GlobalContextManager.getString(
                R.string.wan)
        } else if(likeNum == 0){
            holder.binding.tvCommentActionPraiseCount.text = ""
            holder.binding.tvCommentActionPraiseCount.visibility = View.GONE
        }else {
            holder.binding.tvCommentActionPraiseCount.text = likeNum.toString()
        }
    }

}

